<template>
  <div class="data-upload-container">
    <el-card class="upload-card">
      <!-- 录入方式 -->
      <div class="section">
        <h3 class="section-title">录入方式</h3>
        <el-radio-group v-model="uploadMethod">
          <el-radio label="manual" value="manual">在线录入</el-radio>
          <el-radio label="template" value="template">模板导入</el-radio>
        </el-radio-group>
      </div>

      <el-divider></el-divider>

      <!-- 模板导入模式 -->
      <div v-if="uploadMethod === 'template'">
        <!-- 目标配置 -->
        <div class="section">
          <h3 class="section-title">目标配置</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="config-item">
                <label class="config-label">数据源：</label>
                <el-select
                  v-model="dataSource"
                  placeholder="请选择数据源"
                  style="width: 100%"
                >
                  <el-option
                    label="ods_data(helpipo-任务治理者)"
                    value="ods_data"
                  ></el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="config-item">
                <label class="config-label">数据推送模式：</label>
                <el-select
                  v-model="pushMode"
                  placeholder="请选择推送模式"
                  style="width: 100%"
                >
                  <el-option label="增量追加" value="false"></el-option>
                  <el-option label="全量覆盖" value="true"></el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="config-item">
                <label class="config-label">数据表：</label>
                <el-select
                  v-model="selectedTable"
                  placeholder="请选择数据表"
                  style="width: 100%"
                  :disabled="isDisable"
                >
                  <el-option label="ods_health(卫健委)" value="1"></el-option>
                  <el-option label="ods_police(公安局)" value="2"></el-option>
                  <el-option label="ods_civil(民政局)" value="3"></el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider></el-divider>

        <!-- 数据录入 -->
        <div class="section">
          <h3 class="section-title">数据录入</h3>
          <div class="data-entry-actions">
            <el-button
              type="primary"
              icon="el-icon-download"
              @click="downloadTemplate"
            >
              模板下载
            </el-button>
            <el-button icon="el-icon-view" @click="previewData">
              数据预览
            </el-button>
          </div>
        </div>

        <el-divider></el-divider>

        <!-- 文件上传 -->
        <div class="section">
          <h3 class="section-title">文件上传</h3>
          <file-upload
            :isShowTip="isShowTip"
            :fileType="fileType"
            :uploadUrl="currentURL"
            :key="currentURL"
            :updateSupport="pushMode"
          ></file-upload>
        </div>
      </div>

      <!-- 在线录入模式 -->
      <div v-if="uploadMethod === 'manual'">
        <!-- 数据表选择 -->
        <div class="section">
          <h3 class="section-title">选择数据表</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="config-item">
                <label class="config-label">数据表：</label>
                <el-select
                  v-model="selectedTable"
                  placeholder="请选择数据表"
                  style="width: 100%"
                  @change="handleTableChange"
                  :disabled="isDisable"
                >
                  <el-option label="ods_health(卫健委)" value="1"></el-option>
                  <el-option label="ods_police(公安局)" value="2"></el-option>
                  <el-option label="ods_civil(民政局)" value="3"></el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider></el-divider>

        <!-- 动态表单区域 -->
        <div class="section">
          <h3 class="section-title">数据录入</h3>

          <!-- 根据选择的数据表显示不同的表单 -->
          <div v-if="selectedTable === '1'" class="form-section">
            <!-- 卫健数据表单 -->
            <div class="module-section">
              <div class="module-header">
                <i class="el-icon-first-aid-kit"></i>
                <span class="module-title">卫健数据</span>
                <span class="module-remark">（所有带*字段均为必填）</span>
              </div>
              <el-form
                ref="wjForm"
                :model="wjForm"
                :rules="wjRules"
                :key="selectedTable"
                label-width="140px"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="报告地区名称" prop="bgdqmc">
                      <el-input
                        v-model="wjForm.bgdqmc"
                        placeholder="请输入报告地区名称"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="报告卡编号" prop="bgbh">
                      <el-input
                        v-model="wjForm.bgbh"
                        placeholder="请输入报告卡编号"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="填报单位代码" prop="tbdwdm">
                      <el-input
                        v-model="wjForm.tbdwdm"
                        placeholder="请输入填报单位代码"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="填报单位名称" prop="tbdwmc">
                      <el-input
                        v-model="wjForm.tbdwmc"
                        placeholder="请输入填报单位名称"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="死者姓名" prop="szxm">
                      <el-input
                        v-model="wjForm.szxm"
                        placeholder="请输入死者姓名"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别" prop="xb">
                      <el-select
                        v-model="wjForm.xb"
                        placeholder="请选择性别"
                        clearable
                        style="width: 100%"
                      >
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                        <!-- <el-option label="未知" value="未知" /> -->
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="证件类型" prop="zjlx">
                      <el-select
                        v-model="wjForm.zjlx"
                        placeholder="请选择证件类型"
                        clearable
                        style="width: 100%"
                      >
                        <el-option label="居民身份证" value="居民身份证" />
                        <el-option label="护照" value="护照" />
                        <el-option label="军官证" value="军官证" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="证件号码" prop="zjhm">
                      <el-input
                        v-model="wjForm.zjhm"
                        placeholder="请输入证件号码"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="出生日期" prop="csrq">
                      <el-date-picker
                        v-model="wjForm.csrq"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择出生日期"
                        style="width: 100%"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="民族" prop="mz">
                      <el-input
                        v-model="wjForm.mz"
                        placeholder="请输入民族"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="生前详细地址" prop="szxxdz">
                      <el-input
                        v-model="wjForm.szxxdz"
                        placeholder="请输入生前详细地址"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="户籍详细地址" prop="hjxxdz">
                      <el-input
                        v-model="wjForm.hjxxdz"
                        placeholder="请输入户籍详细地址"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="死亡日期" prop="swrq">
                      <el-date-picker
                        v-model="wjForm.swrq"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择死亡日期"
                        style="width: 100%"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="死亡地点" prop="swdd">
                      <el-input
                        v-model="wjForm.swdd"
                        placeholder="请输入死亡地点"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="家属姓名" prop="jtxm">
                      <el-input
                        v-model="wjForm.jtxm"
                        placeholder="请输入可联系的家属姓名"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="家属联系电话" prop="jtdh">
                      <el-input
                        v-model="wjForm.jtdh"
                        placeholder="请输入家属联系电话"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>

          <div v-if="selectedTable === '2'" class="form-section">
            <!-- 公安数据表单 -->
            <div class="module-section">
              <div class="module-header">
                <i class="el-icon-money"></i>
                <span class="module-title">公安数据</span>
                <span class="module-remark">（所有带*字段均为必填）</span>
              </div>
              <el-form
                ref="gaForm"
                :model="gaForm"
                :rules="gaRules"
                label-width="140px"
                :key="selectedTable"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="姓名" prop="xm">
                      <el-input
                        v-model="gaForm.xm"
                        placeholder="请输入姓名"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别" prop="xb">
                      <el-select
                        v-model="gaForm.xb"
                        placeholder="请选择性别"
                        clearable
                        style="width: 100%"
                      >
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                        <!-- <el-option label="未知" value="未知" /> -->
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="证件号码" prop="sfzh">
                      <el-input
                        v-model="gaForm.sfzh"
                        placeholder="请输入证件号码"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="户籍所在地" prop="hjszd">
                      <el-input
                        v-model="gaForm.hjszd"
                        placeholder="请输入户籍所在地/现住址"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="家属联系方式" prop="jslxfs">
                      <el-input
                        v-model="gaForm.jslxfs"
                        placeholder="请输入家属联系方式"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="死亡时间" prop="swsj">
                      <el-date-picker
                        v-model="gaForm.swsj"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择死亡时间"
                        style="width: 100%"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="死亡原因" prop="swyy">
                      <el-input
                        v-model="gaForm.swyy"
                        placeholder="请输入死亡原因"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>

          <div v-if="selectedTable === '3'" class="form-section">
            <!-- 民政数据表单 -->
            <div class="module-section">
              <div class="module-header">
                <i class="el-icon-office-building"></i>
                <span class="module-title">民政数据</span>
                <span class="module-remark">（所有带*字段均为必填）</span>
              </div>
              <el-form
                ref="mzForm"
                :model="mzForm"
                :rules="mzRules"
                :key="selectedTable"
                label-width="140px"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="逝者编号" prop="szbh">
                      <el-input
                        v-model="mzForm.szbh"
                        placeholder="请输入逝者编号"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="火化时间" prop="hhsj">
                      <el-date-picker
                        v-model="mzForm.hhsj"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择火化时间"
                        style="width: 100%"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="入馆时间" prop="rgsj">
                      <el-date-picker
                        v-model="mzForm.rgsj"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择入馆时间"
                        style="width: 100%"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="逝者姓名" prop="szxm">
                      <el-input
                        v-model="mzForm.szxm"
                        placeholder="请输入逝者姓名"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="性别" prop="xb">
                      <el-select
                        v-model="mzForm.xb"
                        placeholder="请选择性别"
                        clearable
                        style="width: 100%"
                      >
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                        <!-- <el-option label="未知" value="未知" /> -->
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="年龄" prop="nl">
                      <el-input
                        v-model="mzForm.nl"
                        placeholder="请输入年龄"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="证件类型" prop="zjlx">
                      <el-select
                        v-model="mzForm.zjlx"
                        placeholder="请选择证件类型"
                        clearable
                        style="width: 100%"
                      >
                        <el-option label="居民身份证" value="居民身份证" />
                        <el-option label="护照" value="护照" />
                        <el-option label="军官证" value="军官证" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="证件号码" prop="zjhm">
                      <el-input
                        v-model="mzForm.zjhm"
                        placeholder="请输入证件号码"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="户口所在地" prop="hkszd">
                      <el-input
                        v-model="mzForm.hkszd"
                        placeholder="请输入户口所在地"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="生前住址" prop="szdz">
                      <el-input
                        v-model="mzForm.szdz"
                        placeholder="请输入生前住址"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="死亡日期" prop="swrq">
                      <el-date-picker
                        v-model="mzForm.swrq"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择死亡日期"
                        style="width: 100%"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="死亡原因" prop="swyy">
                      <el-input
                        v-model="mzForm.swyy"
                        placeholder="请输入死亡原因"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="承办人姓名" prop="cbrxm">
                      <el-input
                        v-model="mzForm.cbrxm"
                        placeholder="请输入承办人姓名"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系电话" prop="lxdh">
                      <el-input
                        v-model="mzForm.lxdh"
                        placeholder="请输入联系电话"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="与逝者关系" prop="gx">
                      <el-select
                        v-model="mzForm.gx"
                        placeholder="请选择与逝者关系"
                        clearable
                        style="width: 100%"
                      >
                        <el-option label="父子" value="父子" />
                        <el-option label="母子" value="母子" />
                        <el-option label="夫妻" value="夫妻" />
                        <el-option label="兄弟姐妹" value="兄弟姐妹" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="受理人员" prop="slry">
                      <el-input
                        v-model="mzForm.slry"
                        placeholder="请输入受理人员"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>

          <!-- 在线录入操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" @click="handleManualSubmit">
              提交数据
            </el-button>
            <el-button @click="handleManualReset">重置表单</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据预览弹窗 -->
    <el-dialog
      :title="previewTitle"
      :visible.sync="previewVisible"
      width="90%"
      top="5vh"
      append-to-body
    >
      <div v-loading="previewLoading">
        <!-- 卫健数据预览表格 -->
        <div v-if="selectedTable === '1'">
          <el-table
            :data="previewDataList"
            border
            style="width: 100%"
            :key="`preview-table-${selectedTable}-${Date.now()}`"
          >
            <el-table-column label="ID" align="center" prop="id" width="80" />
            <el-table-column
              label="报告地区名称"
              align="center"
              prop="bgdqmc"
            />
            <el-table-column
              label="报告卡编号"
              align="center"
              prop="bgbh"
              width="180"
            />
            <el-table-column
              label="填报单位代码"
              align="center"
              prop="tbdwdm"
            />
            <el-table-column
              label="填报单位名称"
              align="center"
              prop="tbdwmc"
              width="180"
            />
            <el-table-column label="逝者姓名" align="center" prop="szxm" />
            <el-table-column label="性别" align="center" prop="xb" />
            <el-table-column label="证件类型" align="center" prop="zjlx" />
            <el-table-column
              label="证件号码"
              align="center"
              prop="zjhm"
              width="180"
            />
            <el-table-column
              label="出生日期"
              align="center"
              prop="csrq"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.csrq, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="民族" align="center" prop="mz" />
            <el-table-column
              label="生前详细地址"
              align="center"
              prop="szxxdz"
              width="180"
            />
            <el-table-column
              label="户籍详细地址"
              align="center"
              prop="hjxxdz"
              width="180"
            />
            <el-table-column
              label="死亡日期"
              align="center"
              prop="swrq"
              width="180"
            >
              <!-- <template slot-scope="scope">
                <span>{{ parseTime(scope.row.swrq, "{y}-{m}-{d}") }}</span>
              </template> -->
            </el-table-column>
            <el-table-column label="死亡地点" align="center" prop="swdd" />
            <el-table-column
              label="可联系的家属姓名"
              align="center"
              prop="jtxm"
            />
            <el-table-column label="家属联系电话" align="center" prop="jtdh" />
          </el-table>
        </div>

        <!-- 公安数据预览表格 -->
        <div v-if="selectedTable === '2'">
          <el-table
            :data="previewDataList"
            border
            style="width: 100%"
            :key="`preview-table-${selectedTable}-${Date.now()}`"
          >
            <el-table-column label="ID" align="center" prop="id" width="80" />
            <el-table-column label="逝者姓名" align="center" prop="xm" />
            <el-table-column label="性别" align="center" prop="xb" />
            <el-table-column
              label="证件号码"
              align="center"
              prop="sfzh"
              width="180"
            />
            <el-table-column
              label="户籍详细地址"
              align="center"
              prop="hjszd"
              width="180"
            />
            <el-table-column
              label="死亡日期"
              align="center"
              prop="swsj"
              width="180"
            >
              <!-- <template slot-scope="scope">
                <span>{{ parseTime(scope.row.swsj, "{y}-{m}-{d}") }}</span>
              </template> -->
            </el-table-column>
            <el-table-column label="死亡原因" align="center" prop="swyy" />
            <el-table-column
              label="家属联系电话"
              align="center"
              prop="jslxfs"
            />
            <!-- <el-table-column label="上传人" align="center" prop="createBy" /> -->
            <!-- <el-table-column
              label="上传时间"
              align="center"
              prop="createTime"
            /> -->
          </el-table>
        </div>

        <!-- 民政数据预览表格 -->
        <div v-if="selectedTable === '3'">
          <el-table
            :data="previewDataList"
            border
            style="width: 100%"
            :key="`preview-table-${selectedTable}-${Date.now()}`"
          >
            <el-table-column label="ID" align="center" prop="id" width="80" />
            <el-table-column
              label="逝者编号"
              align="center"
              prop="szbh"
              width="150"
            />
            <el-table-column
              label="火化时间"
              align="center"
              prop="hhsj"
              width="100"
            >
              <!-- <template slot-scope="scope">
                <span>{{ parseTime(scope.row.hhsj, "{y}-{m}-{d}") }}</span>
              </template> -->
            </el-table-column>
            <el-table-column
              label="入馆时间"
              align="center"
              prop="rgsj"
              width="100"
            >
              <!-- <template slot-scope="scope">
                <span>{{ parseTime(scope.row.rgsj, "{y}-{m}-{d}") }}</span>
              </template> -->
            </el-table-column>
            <el-table-column label="逝者姓名" align="center" prop="szxm" />
            <el-table-column label="性别" align="center" prop="xb" />
            <el-table-column label="年龄" align="center" prop="nl" />
            <el-table-column label="证件类型" align="center" prop="zjlx" />
            <el-table-column
              label="证件号码"
              align="center"
              prop="zjhm"
              width="180"
            />
            <el-table-column
              label="户口所在地"
              align="center"
              prop="hkszd"
              width="180"
            />
            <el-table-column
              label="生前住址"
              align="center"
              prop="szdz"
              width="180"
            />
            <el-table-column
              label="死亡日期"
              align="center"
              prop="swrq"
              width="100"
            >
              <!-- <template slot-scope="scope">
                <span>{{ parseTime(scope.row.swrq, "{y}-{m}-{d}") }}</span>
              </template> -->
            </el-table-column>
            <el-table-column label="死亡原因" align="center" prop="swyy" />
            <el-table-column label="承办人姓名" align="center" prop="cbrxm" />
            <el-table-column label="联系电话" align="center" prop="lxdh" />
            <el-table-column label="与逝者关系" align="center" prop="gx" />
            <el-table-column label="受理人员" align="center" prop="slry" />
          </el-table>
        </div>

        <!-- 分页组件 -->
        <!-- <pagination
          v-show="previewTotal > 0"
          :total="previewTotal"
          :page.sync="previewQueryParams.pageNum"
          :limit.sync="previewQueryParams.pageSize"
          @pagination="handlePreview"
        /> -->
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSwxx } from "@/api/system/swxx";
import { addSwmd } from "@/api/system/swmd";
import { addHhjl } from "@/api/system/hhjl";
import { listSwxx } from "@/api/system/swxx";
import { listSwmd } from "@/api/system/swmd";
import { listHhjl } from "@/api/system/hhjl";
import { searchLog } from "@/api/system/list";

export default {
  name: "DataUpload",
  data() {
    return {
      uploadMethod: "manual",
      dataSource: "ods_data",
      pushMode: "false",
      selectedTable: "1",
      isDisable: true,
      primaryKeyConflict: "replace",
      fileList: [],
      isShowTip: true,
      fileType: ["xls", "xlsx"],

      // 数据预览相关
      previewVisible: false,
      previewLoading: false,
      previewDataList: [],
      previewTotal: 0,
      previewQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },

      // 在线录入表单数据
      wjForm: {
        bgdqmc: null,
        bgbh: null,
        tbdwdm: null,
        tbdwmc: null,
        szxm: null,
        xb: null,
        zjlx: null,
        zjhm: null,
        csrq: null,
        mz: null,
        szxxdz: null,
        hjxxdz: null,
        swrq: null,
        swdd: null,
        jtxm: null,
        jtdh: null,
      },
      gaForm: {
        xm: null,
        xb: null,
        sfzh: null,
        hjszd: null,
        jslxfs: null,
        swsj: null,
        swyy: null,
      },
      mzForm: {
        szbh: null,
        hhsj: null,
        rgsj: null,
        szxm: null,
        xb: null,
        nl: null,
        zjlx: null,
        zjhm: null,
        hkszd: null,
        szdz: null,
        swrq: null,
        swyy: null,
        cbrxm: null,
        lxdh: null,
        gx: null,
        slry: null,
      },

      // 表单验证规则
      wjRules: {
        bgdqmc: [
          { required: true, message: "报告地区名称不能为空", trigger: "blur" },
        ],
        bgbh: [
          { required: true, message: "报告卡编号不能为空", trigger: "blur" },
        ],
        tbdwdm: [
          { required: true, message: "填报单位代码不能为空", trigger: "blur" },
        ],
        tbdwmc: [
          { required: true, message: "填报单位名称不能为空", trigger: "blur" },
        ],
        szxm: [
          { required: true, message: "死者姓名不能为空", trigger: "blur" },
        ],
        xb: [{ required: true, message: "性别不能为空", trigger: "change" }],
        zjlx: [
          { required: true, message: "证件类型不能为空", trigger: "change" },
        ],
        zjhm: [
          { required: true, message: "证件号码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.validateIdCard(value)) {
                callback(new Error("请输入正确的身份证号码格式"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        csrq: [
          { required: true, message: "出生日期不能为空", trigger: "change" },
        ],
        mz: [{ required: true, message: "民族不能为空", trigger: "blur" }],
        szxxdz: [
          { required: true, message: "生前详细地址不能为空", trigger: "blur" },
        ],
        hjxxdz: [
          { required: true, message: "户籍详细地址不能为空", trigger: "blur" },
        ],
        swrq: [
          { required: true, message: "死亡日期不能为空", trigger: "change" },
        ],
        swdd: [
          { required: true, message: "死亡地点不能为空", trigger: "blur" },
        ],
        jtxm: [
          { required: true, message: "家属姓名不能为空", trigger: "blur" },
        ],
        jtdh: [
          { required: true, message: "家属联系电话不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.validatePhone(value)) {
                callback(new Error("请输入正确的手机号码格式"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      gaRules: {
        xm: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        xb: [{ required: true, message: "性别不能为空", trigger: "change" }],
        sfzh: [
          { required: true, message: "证件号码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.validateIdCard(value)) {
                callback(new Error("请输入正确的身份证号码格式"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        hjszd: [
          { required: true, message: "户籍所在地不能为空", trigger: "blur" },
        ],
        jslxfs: [
          { required: true, message: "家属联系方式不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.validatePhone(value)) {
                callback(new Error("请输入正确的手机号码格式"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        swsj: [
          { required: true, message: "死亡时间不能为空", trigger: "change" },
        ],
        swyy: [
          { required: true, message: "死亡原因不能为空", trigger: "blur" },
        ],
      },
      mzRules: {
        szbh: [
          { required: true, message: "逝者编号不能为空", trigger: "blur" },
        ],
        hhsj: [
          { required: true, message: "火化时间不能为空", trigger: "change" },
        ],
        rgsj: [
          { required: true, message: "入馆时间不能为空", trigger: "change" },
        ],
        szxm: [
          { required: true, message: "逝者姓名不能为空", trigger: "blur" },
        ],
        xb: [{ required: true, message: "性别不能为空", trigger: "change" }],
        nl: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
        zjlx: [
          { required: true, message: "证件类型不能为空", trigger: "change" },
        ],
        zjhm: [
          { required: true, message: "证件号码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.validateIdCard(value)) {
                callback(new Error("请输入正确的身份证号码格式"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        hkszd: [
          { required: true, message: "户口所在地不能为空", trigger: "blur" },
        ],
        swrq: [
          { required: true, message: "死亡日期不能为空", trigger: "change" },
        ],
        cbrxm: [
          { required: true, message: "承办人姓名不能为空", trigger: "blur" },
        ],
        lxdh: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.validatePhone(value)) {
                callback(new Error("请输入正确的手机号码格式"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        gx: [
          { required: true, message: "与逝者关系不能为空", trigger: "change" },
        ],
        slry: [
          { required: true, message: "受理人员不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    currentURL() {
      const urlMap = {
        1: "/system/swxx/importData", //卫健
        2: "/system/swmd/importData", //公安
        3: "/system/hhjl/importData", //民政
      };
      return urlMap[this.selectedTable] || "";
    },
    previewTitle() {
      const titleMap = {
        1: "卫健数据预览",
        2: "公安数据预览",
        3: "民政数据预览",
      };
      return titleMap[this.selectedTable] || "数据预览";
    },
  },
  created() {
    this.initSelectedTableByRole();
  },
  methods: {
    // 身份证号码验证
    validateIdCard(idCard) {
      if (!idCard) {
        return false;
      }

      // 移除前后空格
      idCard = idCard.toString().trim();

      // 宽松格式验证：允许15位或18位
      const idCardReg = /^(\d{15}$)|(^\d{17}(\d|X|x)$)/;
      if (!idCardReg.test(idCard)) {
        return false;
      }

      // 如果是18位，进行校验码验证（但允许校验码错误）
      if (idCard.length === 18) {
        const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        const checksumMap = [
          "1",
          "0",
          "X",
          "9",
          "8",
          "7",
          "6",
          "5",
          "4",
          "3",
          "2",
        ];

        let sum = 0;
        for (let i = 0; i < 17; i++) {
          sum += parseInt(idCard.charAt(i)) * factors[i];
        }

        const checksum = checksumMap[sum % 11];

        // 宽松模式：如果校验码不正确，只给出警告但不拒绝
        if (checksum !== idCard.charAt(17).toUpperCase()) {
          console.warn("身份证校验码不正确，但允许通过");
          // 这里可以返回true或者false，根据你的需求
          return true; // 宽松模式：允许校验码错误
        }
      }

      return true;
    },

    // 手机号码验证
    validatePhone(phone) {
      // const phoneReg = /^1[3-9]\d{9}$/;
      // return phoneReg.test(phone);
      return true
    },
    // 根据用户角色初始化selectedTable
    initSelectedTableByRole() {
      // 获取当前用户信息，这里假设用户信息存储在store或localStorage中
      // 若依框架通常可以通过this.$store.getters.roles获取用户角色
      const roles = this.$store?.getters?.roles || [];

      if (roles.includes("wj")) {
        this.selectedTable = "1"; // 卫健
      } else if (roles.includes("ga")) {
        this.selectedTable = "2"; // 公安
      } else if (roles.includes("mz")) {
        this.selectedTable = "3"; // 民政
      } else if (roles.includes("admin")) {
        // console.log("roles.includes", roles.includes("admin"));
        this.isDisable = false; // 民政
      }
      // 默认值已经在data中设置为'1'，所以不需要else
    },

    handleTableChange(e) {
      console.log("3eee", e);
      // 清除所有表单的校验状态
      ["wjForm", "gaForm", "mzForm"].forEach((formRef) => {
        if (this.$refs[formRef]) {
          this.$refs[formRef].clearValidate();
        }
      });
    },

    resetAllForms(e) {
      this.wjForm = this.getDefaultWjForm();
      this.gaForm = this.getDefaultGaForm();
      this.mzForm = this.getDefaultMzForm();
      this.selectedTable = e;
    },

    getDefaultWjForm() {
      return {
        bgdqmc: null,
        bgbh: null,
        tbdwdm: null,
        tbdwmc: null,
        szxm: null,
        xb: null,
        zjlx: null,
        zjhm: null,
        csrq: null,
        mz: null,
        szxxdz: null,
        hjxxdz: null,
        swrq: null,
        swdd: null,
        jtxm: null,
        jtdh: null,
      };
    },

    getDefaultGaForm() {
      return {
        xm: null,
        xb: null,
        sfzh: null,
        hjszd: null,
        jslxfs: null,
        swsj: null,
        swyy: null,
      };
    },

    getDefaultMzForm() {
      return {
        szbh: null,
        hhsj: null,
        rgsj: null,
        szxm: null,
        xb: null,
        nl: null,
        zjlx: null,
        zjhm: null,
        hkszd: null,
        szdz: null,
        swrq: null,
        swyy: null,
        cbrxm: null,
        lxdh: null,
        gx: null,
        slry: null,
      };
    },

    // 下载模板
    downloadTemplate() {
      const res = this.selectedTable;
      if (res == 3) {
        this.download("system/hhjl/importTemplate", {}, `MZ_导入模板.xlsx`);
      } else if (res == 1) {
        this.download("system/swxx/importTemplate", {}, `WJ_导入模板.xlsx`);
      } else if (res == 2) {
        this.download("system/swmd/importTemplate", {}, `GA_导入模板.xlsx`);
      }
    },

    // 数据预览
    previewData() {
      this.previewQueryParams.pageNum = 1;
      this.handlePreview();
    },

    // 处理数据预览
    handlePreview() {
      this.previewLoading = true;
      this.previewVisible = true;

      // 先清空数据
      this.previewDataList = [];

      let deptFlag = { deptFlag: parseInt(this.selectedTable) };

      searchLog(deptFlag)
        .then((response) => {
          // 使用 setTimeout 确保在下一个事件循环中更新
          setTimeout(() => {
            // 深度拷贝数据
            this.previewDataList = JSON.parse(
              JSON.stringify(response.data || [])
            );

            this.$nextTick(() => {
              this.previewLoading = false;
              // 双重保障：强制更新
              this.$forceUpdate();
            });
          }, 0);
        })
        .catch((error) => {
          console.error("预览数据失败:", error);
          this.previewLoading = false;
          this.$message.error("获取数据失败");
        });
    },

    // 提交上传（模板导入）
    handleSubmit() {
      if (this.fileList.length === 0) {
        this.$message.warning("请先上传文件");
        return;
      }

      this.$confirm("确认提交数据上传吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message.success("数据上传提交成功");
        })
        .catch(() => {
          this.$message.info("已取消提交");
        });
    },

    // 重置表单（模板导入）
    handleReset() {
      this.uploadMethod = "manual";
      this.dataSource = "ods_data";
      this.pushMode = "false";
      this.primaryKeyConflict = "replace";
      this.fileList = [];
    },

    // 提交在线录入数据
    handleManualSubmit() {
      let formData = {};
      let formRef = null;
      let apiMethod = null;

      // 根据选择的数据表获取对应的表单数据和引用
      if (this.selectedTable === "1") {
        formData = { ...this.wjForm };
        formRef = this.$refs.wjForm;
        apiMethod = addSwxx;
      } else if (this.selectedTable === "2") {
        formData = { ...this.gaForm };
        formRef = this.$refs.gaForm;
        apiMethod = addSwmd;
      } else if (this.selectedTable === "3") {
        formData = { ...this.mzForm };
        formRef = this.$refs.mzForm;
        apiMethod = addHhjl;
      }

      if (!formRef || !apiMethod) {
        this.$message.error("请选择数据表");
        return;
      }

      // 表单验证
      formRef.validate((valid) => {
        if (valid) {
          // 民政数据特殊校验
          if (this.selectedTable === "3") {
            if (this.mzForm.swrq) {
              const deathDate = new Date(this.mzForm.swrq);
              const entryTime = new Date(this.mzForm.rgsj);
              const cremationTime = new Date(this.mzForm.hhsj);

              if (deathDate >= entryTime) {
                this.$modal.msgError("死亡日期必须早于入馆时间");
                return;
              }

              if (deathDate >= cremationTime) {
                this.$modal.msgError("死亡日期必须早于火化时间");
                return;
              }
            }
          }

          this.$confirm("确认提交数据吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              // 调用对应的新增接口
              apiMethod(formData)
                .then((response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.handleManualReset();
                })
                .catch((error) => {
                  this.$modal.msgError("新增失败");
                });
            })
            .catch(() => {
              this.$message.info("已取消提交");
            });
        } else {
          this.$message.error("请填写完整的表单信息");
          return false;
        }
      });
    },

    // 重置在线录入表单
    handleManualReset() {
      if (this.selectedTable === "1") {
        this.wjForm = {
          bgdqmc: null,
          bgbh: null,
          tbdwdm: null,
          tbdwmc: null,
          szxm: null,
          xb: null,
          zjlx: null,
          zjhm: null,
          csrq: null,
          mz: null,
          szxxdz: null,
          hjxxdz: null,
          swrq: null,
          swdd: null,
          jtxm: null,
          jtdh: null,
        };
        this.$refs.wjForm && this.$refs.wjForm.resetFields();
      } else if (this.selectedTable === "2") {
        this.gaForm = {
          xm: null,
          xb: null,
          sfzh: null,
          hjszd: null,
          jslxfs: null,
          swsj: null,
          swyy: null,
        };
        this.$refs.gaForm && this.$refs.gaForm.resetFields();
      } else if (this.selectedTable === "3") {
        this.mzForm = {
          szbh: null,
          hhsj: null,
          rgsj: null,
          szxm: null,
          xb: null,
          nl: null,
          zjlx: null,
          zjhm: null,
          hkszd: null,
          szdz: null,
          swrq: null,
          swyy: null,
          cbrxm: null,
          lxdh: null,
          gx: null,
          slry: null,
        };
        this.$refs.mzForm && this.$refs.mzForm.resetFields();
      }
    },
  },
};
</script>

<style scoped>
.data-upload-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.upload-card {
  min-width: 1000px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section {
  margin-bottom: 20px;
}

.section-title {
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  padding-left: 8px;
  border-left: 4px solid #409eff;
}

.config-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.config-label {
  min-width: 120px;
  color: #606266;
  font-weight: 500;
}

.data-entry-actions {
  display: flex;
  gap: 15px;
}

.action-buttons {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

.action-buttons .el-button {
  min-width: 120px;
  margin: 0 10px;
}

/* 模块样式 */
.module-section {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #f8f9fa;
}

.module-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
}

.module-header i {
  font-size: 18px;
  margin-right: 8px;
}

.module-title {
  font-size: 16px;
  font-weight: 600;
}
</style>